﻿using PLCS.App.Shared.Models;
using PLCS.App.Shared.Service;
using PLCS.App.Shared.ViewModels;
using PLCS.Client.IService.ConfigManager;
using System.Collections.Generic;
using System.Reflection;
using Volo.Abp.Domain.Repositories;

namespace PLCS.App.ViewModels.Dialogs
{
    public class SettingViewModel : HostDialogViewModel
    {
        private CacheSetting _cacheSetting;
        private readonly IConfigService _configService;
        private readonly CacheSettingService _cacheSettingService;

        public CacheSetting Model
        {
            get { return _cacheSetting; }
            set { SetProperty(ref _cacheSetting, value); }
        }

        public string Title => "设置";

        public event Action<IDialogResult> RequestClose;

        public SettingViewModel(IConfigService configService, CacheSettingService cacheSettingService)
        {
            _configService = configService;
            _cacheSettingService = cacheSettingService;
        }

        protected override async void Save()
        {
            try
            {
                await _cacheSettingService.UpdateCacheSetting(Model);
                DialogHost.Close(IdentifierName, new DialogResult(ButtonResult.OK));
                ShowMessage("配置成功，重启程序后发生改变。");
            }
            catch (Exception ex)
            {
                ShowMessage($"配置失败，失败原因：{ex.Message}。");
            }
        }

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
        }

        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            Model = await _cacheSettingService.InitalCacheSetting();
        }

        public static List<string> GetPropertyNames(Type type)
        {
            List<string> propertyNames = new List<string>();
            foreach (var property in type.GetProperties())
            {
                propertyNames.Add(property.Name);
            }
            return propertyNames;
        }
    }
}